package diona.snippet.requests

import net.liftweb.http.js.{JsCmds, JsCmd}
import net.liftweb.util.BindHelpers._
import diona.components.{ProfileInfoComponent, PostsComponent}
import diona.search.yasearch.{YaProfilesSearch, YaBlogsSearch}
import net.liftweb.http.{S, StatefulSnippet, SHtml}
import xml.{Text, NodeSeq}
import diona.search.{SearchItem, SearchRequest, PostInfo}
import diona.model.pages.PageInfo

/**
 * User: anton
 * Date: 05.07.11 21:37
 */
class SearchResults() extends StatefulSnippet
{

  private var query = ""
  private var requestId: Option[Long] = None

  def processQuery(): JsCmd =
  {
    hidePostDetails &
      JsCmds.SetHtml("posts", renderPosts())
  }

  def hidePostDetails: JsCmds.Run =
  {
    JsCmds.Run("$('#postDetails').hide();")
  }

  def showPost(post: PostInfo): JsCmd =
  {
    hidePostDetails &
      JsCmds.Run(SHtml.ajaxInvoke(() => {
        val js = for {
          author <- post.author
          profile <- YaProfilesSearch.search(author)
        } yield {
          JsCmds.SetHtml("postDetails", ProfileInfoComponent(profile)) &
            JsCmds.Run("$('#postDetails').fadeIn('fast');")
        }
        js.getOrElse(JsCmds.Noop)
      })._2.toJsCmd)
  }

  def renderPosts() =
  {
    val posts = requestId match {
      case Some(id) => PageInfo.byRequestId(id).map(PageInfo.toPostInfo(_))
      case None => YaBlogsSearch.search(query)
    }
    new PostsComponent(posts, Some(showPost)).render()
  }

  def dispatch =
  {
    case "render" => render
    case "searchForm" => searchForm
    case "showPosts" => showPosts()
  }

  def showPosts() = "*" #> renderPosts()

  def searchForm(html: NodeSeq): NodeSeq =
  {
    val cssSel = "#query" #> SHtml.text(query, query = _, "id" -> "the_query") &
      "#submit" #> (SHtml.hidden(processQuery _) ++ SHtml.submit("Search", processQuery _, "id" -> "sbmt"))
    SHtml.ajaxForm(cssSel(html))
  }

  def render =
  {
    "#defaultPosts" #> {
      requestId = S.param("requestId").map(_.toLong).toOption
      requestId match {
        case Some(id) => {
          val request = SearchRequest.byId(id)
          query = request.query.is
          <lift:lazy-load>
            <div class="lift:requests/SearchResults.showPosts"/>
          </lift:lazy-load>
        }
        case None => Text("")
      }
    }
  }
}